package dk.sdu.flexibus.addressvalidator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import dk.sdu.flexibus.lib.TwoTuple;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;

public class GeocodingTask extends
		AsyncTask<String, Void, TwoTuple<String, Boolean>> {
	Context context;
	private double lowerLeftLatitude;
	private double lowerLeftLongitude;
	private double upperRightLatitude;
	private double upperRightLongitude;
	private AddressValidator addressValidator;

	public GeocodingTask(Context context, AddressValidator addressValidator,
			double lowerLeftLatitude, double lowerLeftLongitude,
			double upperRightLatitude, double upperRightLongitude) {
		super();
		this.context = context;
		this.addressValidator = addressValidator;
		this.lowerLeftLatitude = lowerLeftLatitude;
		this.lowerLeftLongitude = lowerLeftLongitude;
		this.upperRightLatitude = upperRightLatitude;
		this.upperRightLongitude = upperRightLongitude;

	}

	@Override
	protected TwoTuple<String, Boolean> doInBackground(String... params) {
		Geocoder geocoder = new Geocoder(context, Locale.getDefault());
		String address = params[0];
		List<Address> addresses = new ArrayList<Address>();
		try {
			addresses = geocoder.getFromLocationName(address, 5,
					lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude,
					upperRightLongitude);
		} catch (IOException e) {
		}
		return new TwoTuple<String, Boolean>(address, (addresses.size() == 1));
	}

	@Override
	protected void onPostExecute(TwoTuple<String, Boolean> result) {
		super.onPostExecute(result);
		addressValidator.notifyValidationListeners(result.getFirst(), result.getSecond());

	}
}
